import { 
    getMasterBrandList,
    getMakeListByMaster
} from '@/api/carList'

const state = {
    brand: {},
    letters: [],
    brandCars: [],
    yearList: {}
}

const actions = {
    async init({ commit }) {
        let res = await getMasterBrandList()
        let brand = {}
        let letters = res.data.data.map(item => item.Spelling.slice(0, 1))
        // 类数组转换为真正的数组
        letters = Array.from(new Set(letters))
        
        res.data.data.forEach(item => {
            const initial = item.Spelling.slice(0, 1)
            // 给对象添加Key
            if (brand[initial]) {
                brand[initial].push(item)
            } else {
                // 如果是首次添加
                brand[initial] = [item]
            }
        })

        // 提交mutations中的函数
        commit("setBrand", brand)
        commit("setLetters", letters)
    },
    // 获取品牌车系
    async getBrandCars({ commit }, params) {
        let res = await getMakeListByMaster(params)
        commit("setBrandCars", res.data.data)
    }
}

const mutations = {
    setBrand(state, obj) {
        state.brand = obj
    },
    setLetters(state, letters) {
        state.letters = letters
    },
    // 对品牌车系赋值
    setBrandCars(state, brandCars) {
        state.brandCars = brandCars
        console.log(state.brandCars)
    },
    setYearList(state, yearList) {
        state.yearList = yearList
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations
}